package com.cjet.nissan.tcp.codec;

import android.os.Handler;

import com.cjet.nissan.tcp.INetty;
import com.cjet.nissan.tcp.bean.TcpData;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ImprovedDecoder extends ByteToMessageDecoder {

    public enum State {
        INIT, READING_DATA
    }

    private State state = State.INIT;

    private int mDoDecodeCount = 0;
    private Handler mMainHandler;
    private INetty.OnChannelHandler onChannelHandler;
    public ImprovedDecoder(Handler mMainHandler,INetty.OnChannelHandler onChannelHandler){
        this.mMainHandler =mMainHandler;
        this.onChannelHandler =onChannelHandler;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        while (in.readableBytes() > 0) {
            switch (state) {
                case INIT:
                    if (in.readShort() == 0xFA1B) {
                         //有效数据的时候，重置计数
                        mDoDecodeCount = 0 ;
                        state = State.READING_DATA;
                        // 读取指令符号、数据长度等
                        short command = in.readShort();
                        int length = in.readUnsignedByte();

                        // 创建数据对象，并根据指令符号进行不同的解析
                        TcpData data = new TcpData();
                        switch (command) {
                            case 0x0001:
                                // 解析指令0x0001对应的具体数据
//                                data.setField1(in.readInt());
//                                data.setField2(in.readShort());
                                break;
                            case 0x0002:
                                // 解析指令0x0002对应的具体数据
                                byte[] bytes = new byte[length - 4];
                                in.readBytes(bytes);
//                                data.setData(bytes);
                                break;
                            default:
                                // 未知指令，丢弃数据
                                in.skipBytes(length);
                                break;
                        }
                        if (onChannelHandler != null) {
                            mMainHandler.post(() -> onChannelHandler.onMessageReceived(ctx, data));
                        }
                        out.add(data);
                    } else {
                        // 丢弃当前字节，并考虑是否关闭连接
                        in.readByte();
                        // 如果连续遇到多个无效字节，可以考虑关闭连接
                         // 判断连续无效字节的数量
                        if (mDoDecodeCount > 10) {
                            ctx.channel().close();
                        }else {
                            mDoDecodeCount++;
                        }
                    }
                    break;
                case READING_DATA:
                    // ... (解析数据部分)// 遇到包尾
                    if (in.readShort() == 0xFA2C) {
                        state = State.INIT;
                    } else {
                        // 遇到错误，重置状态机，丢弃当前缓冲区数据
                        state = State.INIT;
                        in.clear();
                        // 可以记录错误日志，或者触发其他异常处理机制
                        ctx.fireExceptionCaught(new Exception("Invalid data"));
                    }
                    break;
            }
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        if (onChannelHandler != null) {
            mMainHandler.post(() -> onChannelHandler.onExceptionCaught(ctx, cause));
        }
    }
}